<?php
class multitender_action_graph extends multitender_action {
    const WEEKS = 20;
    const MONTHS = 12;

    function  __construct() {
        parent::__construct();
        $rights = $this->conf['user']['right'];
        if ($rights <= 1) {
    	    $tpl = $this->new_tpl();
    	    $tpl->display("msg_right.tpl");
    	    exit;
        }
    }
    
    public function run() {
        $from = mktime(0, 0, 0, date('m')-5, 1, date('Y'));
        $to = mktime(23, 59, 59, date('m'), date('d'), date('Y'));
        
        if (isset($_GET['from']) && isset($_GET['to']) && isset($_GET['group'])) {
            $from = strtotime($_GET['from']);
            $to = strtotime($_GET['to'].' 23:59:59');
            $group = (int) $_GET['group'];
            $action = $_GET['active'];
            $cmp = (int) $_GET['cmp'];
            if ($cmp == 1) {
                $to_cmp = strtotime($_GET['to_cmp'].' 23:59:59');
                $from_cmp = strtotime($_GET['from_cmp']);
                $this->format($from_cmp, $to_cmp, $group);
            } else {
                $from_cmp = 0;
                $to_cmp = 0;
            }
            
            $this->format($from, $to, $group);
            
            $serial = "graph_$from:$to:$group:$action:$from_cmp:$to_cmp";
            
            $model = $this->new_model('graph');
            
            switch ($action) {
                case 'payments':
                    $data = $model->getNewPayments2($from, $to, $group, $from_cmp, $to_cmp);
                    if ($data != null) {
                        $data = $this->transformToJSON($data, $group, $from_cmp, $to_cmp);
                    }
                break;
                case 'money':
                    $data = $model->getMoney2($from, $to, $group, $from_cmp, $to_cmp);
                    if ($data != null) {
                        $data = $this->transformToJSON($data, $group, $from_cmp, $to_cmp);
                    }
                break;
                case 'regs':
                    $data = $model->getNewRegs2($from, $to, $group, $from_cmp, $to_cmp);
                    if ($data != null) {
                        $data = $this->transformToJSON($data, $group, $from_cmp, $to_cmp);
                    }
                break;
                case 'new_tenders':
                    $memcache = new Memcache;
                    $memcache->connect('localhost', 11611);
                    $data = $memcache->get($serial);
                    if ($data === FALSE) {
                        $data = $model->getNewTenders2($from, $to, $group, $from_cmp, $to_cmp);
                        if ($data != null) {
                            $data = $this->transformToJSON($data, $group, $from_cmp, $to_cmp);
                        }
                        $memcache->set($serial, $data, MEMCACHE_COMPRESSED, 43200);
                    }
                break;
                case 'new_moderator':
                    $memcache = new Memcache;
                    $memcache->connect('localhost', 11611);
                    $data = $memcache->get($serial);
                    if ($data === FALSE) {
                        $data = $model->getNewModerator2($from, $to, $group, $from_cmp, $to_cmp);
                        if ($data != null) {
                            $data = $this->transformToJSON($data, $group, $from_cmp, $to_cmp);
                        }
                        $memcache->set($serial, $data, MEMCACHE_COMPRESSED, 43200);
                    }
                break;
                case 'payed_nonpayed':
                    $data = $model->getPayedNonpayed2($from, $to, $group, $from_cmp, $to_cmp);
                    if ($data != null) {
                        $data = $this->transformToJSON($data, $group, $from_cmp, $to_cmp);
                    }
                break;
                case 'com_gos':
                    $data = $model->getCommercial2($from, $to, $group, $from_cmp, $to_cmp);
                    if ($data != null) {
                        $data = $this->transformToJSON($data, $group, $from_cmp, $to_cmp);
                    }
                break;
                case 'ending':
                    $data = $model->getEnding2($from, $to, $group, $from_cmp, $to_cmp);
                    if ($data != null) {
                        $data = $this->transformToJSON($data, $group, $from_cmp, $to_cmp);
                    }
                break;
            }
            
            echo $data;
            exit();
        }

        $this->conf['page_title'] = 'Графики';
        $tpl = $this->new_tpl();
        //$tpl->caching = TRUE;
        //$tpl->cache_lifetime = 60*60;
        //if ($tpl->is_cached('graph.tpl')) {
        //    return $tpl->fetch('graph.tpl');
        //}
        $fetch = '';
        
        /*
        $grapher = $this->new_action('grapher');
        // ********** WEEKS ************
        $fetch .= "Обновлено " . date("j m Y, G:i a");
        $fetch .= '<h3>Статистика за последние ' . self::WEEKS . ' недель</h3>';
        $data = $model->getNewPayments('week', '2010');
        $diff = $this->diffProc($data[0], $data[1]);

        $data[0] = $this->week_to_date($data[0]);
        $data[1] = $this->week_to_date($data[1]);
        $fetch .= $grapher->draw_column(array('Оплатившие впервые' => $data[0], 'Всего платежей'=>$data[1]),
                'Впервые оплатившие', '');
        //$fetch .= $grapher->draw_column(array('%' => $this->week_to_date($diff)),
        //      'Отношение впервые оплативших ко всем оплатившим', '', 740, 150);
        
        $data = $model->getNewRegs('week');
        $data[0] = $this->week_to_date($data[0]);
        $fetch .= $grapher->draw_column(array('Количество регистраций'=>$this->toProc($data[0])),
        'Количество регистраций', '');

        $data = $model->getNewItems('week');
        $data[0] = $this->week_to_date($data[0]);
        $fetch .= $grapher->draw_column(array('Новых тендеров'=>$this->toProc($data[0])),
        'Количество новых тендеров', '');

        $data = $model->getItemsByModer('week');
        $data[0] = $this->week_to_date($data[0]);
        $fetch .= $grapher->draw_column(array('Новых тендеров'=>$this->toProc($data[0])),
        'Количество новых тендеров от модератора', '');

        $data = $model->getMoney('week');
        $temp1 = array();
        $temp2 = array();
        if (count($data[2])>0) {
            foreach($data[2] as $key => $el) {
                if (!isset($data[0][$key])) {
                    $temp1[$key] = 0;
                } else {
                    $temp1[$key] = $data[0][$key];
                }

                if (!isset($data[1][$key])) {
                    $temp2[$key] = 0;
                } else {
                    $temp2[$key] = $data[1][$key];
                }
            }
        }
        $data[1] = $temp2;
        $data[0] = $temp1;
        $data[0] = $this->week_to_date($data[0]);
        $data[1] = $this->week_to_date($data[1]);
        $data[2] = $this->week_to_date($data[2]);
        
        $fetch .= $grapher->draw_column(array('Сумма'=>$data[2], 'Безналичный расчет' => $data[1], 'Эл. платежи'=>$data[0]),
        'Деньги', '');

        // ********** MONTHS ************
        $fetch .= '<h3>Статистика за последние ' . self::MONTHS . ' месяцев</h3>';
        $data = $model->getNewPayments('year', '2010');

        foreach ($data as &$el) {
            $el = $this->num_to_month($el);
        }
        $fetch .= $grapher->draw_column(array('Оплатившие впервые' => $data[0], 'Всего платежей'=>$data[1]),
                'Впервые оплатившие', '');

        $data = $model->getNewRegs('year');
        $data[0] = $this->num_to_month($data[0]);
        $fetch .= $grapher->draw_column(array('Количество регистраций'=>$this->toProc($data[0])),
        'Количество регистраций', '');

        $data = $model->getNewItems('year');
        $data[0] = $this->num_to_month($data[0]);
        $fetch .= $grapher->draw_column(array('Новых тендеров'=>$this->toProc($data[0])),
        'Количество новых тендеров', '');

        $data = $model->getItemsByModer('year');
        $data[0] = $this->num_to_month($data[0]);
        $fetch .= $grapher->draw_column(array('Новых тендеров'=>$this->toProc($data[0])),
        'Количество новых тендеров от модератора', '');

        $data = $model->getMoney('year');

        $temp1 = array();
        $temp2 = array();
        if (count($data[2])>0) {
            foreach($data[2] as $key => $el) {
                if (!isset($data[0][$key])) {
                    $temp1[$key] = 0;
                } else {
                    $temp1[$key] = $data[0][$key];
                }

                if (!isset($data[1][$key])) {
                    $temp2[$key] = 0;
                } else {
                    $temp2[$key] = $data[1][$key];
                }
            }
        }
        $data[1] = $temp2;
        $data[0] = $temp1;
        
        foreach ($data as &$el) {
            $el = $this->num_to_month($el);
        }

        $fetch .= $grapher->draw_column(array('Сумма'=>$data[2], 'Безналичный расчет' => $data[1], 'Эл. платежи'=>$data[0]),
        'Деньги', '');*/
        
        $tpl->assign('from', date('d.m.Y', $from));
        $tpl->assign('to', date('d.m.Y', $to));
        $tpl->assign('fetch', $fetch);
        return $tpl->fetch('graph.tpl');
    }
    
    function transformToJSON($data, $group) {
        $json = '"plots": [';
        $i = 1;
        foreach ($data as $plot) {
            //$json .= '"plot'.$i.'": ';
            $row = '[';
            foreach ($plot as $dot_name => $dot) {
                $row .= '["'.$this->transform_date($dot_name, $group).'", '.$dot['value'].', "'.$dot['label'].'"],';
            }
            $row = trim($row, ',');
            $json .= $row.'], ';
            $i++;
        }
        $json = trim($json, ', ');
        $json .= ']';
        return '{'.$json.'}';
    }
    
    function num_to_month($array) {
        if (!is_array($array)) {
            return array();
        }
        $months = array('Нулябрь', 'Январь','Февраль','Март','Апрель','Май','Июнь','Июль','Август','Сентябрь','Октябрь','Ноябрь','Декабрь');
        $result = array();
        foreach ($array as $key => $element) {
            $key = explode('-', $key);
            if (isset($months[$key[1]])) {
                $result[$months[$key[1]].' '.$key[0]] = $element;
            }
        }
        return $result;
    }


    function week_to_date($array) {
        if (!is_array($array)) {
            return array();
        }
        foreach ($array as $key => $element) {
            $key = explode('-', $key);
            $clear[$this->getDateFormYAndW($key[0], $key[1])] = $element;
        }
        return $clear;
    }

    function getDateFormYAndW($year, $week) {
        $dayOfWeek = date("w", mktime(0, 0, 0, 1, 1, $year));
        if ($dayOfWeek == 0) {
            $dayOfWeek = 7;
        }
        switch ($dayOfWeek) {
            case 1:
                $date = date("d.m.y", mktime(0, 0, 0, 1, 1, $year));
                break;
            default:
                $date = date("d.m.y", mktime(0, 0, 0, 12, 31 + 2 - $dayOfWeek, $year-1));
        }
        $date = strtotime($date) + (60*60*24*(7*($week)));
        return date("d M Y", $date);
    }

    private function toProc($data, $data2 = array(), $data3 = array()) {
        $result = array();
        foreach ($data as $date => $value) {
            if (isset($last)) {
                $change = 100 - round($value * 100 / $last);
                $change = 0 - $change;
                $change = ' (' . $change . '%)';
                $result[$date . $change] = $value;
            } else {
                $result[$date] = $value;
            }
            $last = $value;
        }
        return $result;

    }

    private function diffProc($data1, $data2) { // data1 > data2
        $result = array();

        $i=0;
        foreach ($data1 as $date1 => $d1) {
            foreach ($data2 as $date2 => $d2) {
                if ($date1 == $date2) {
                    $result[$date1] = $d1 * 100 / $d2;
                    $result[$date1] = round($result[$date1]);
                }
            }
            
            $i++;
        }
        return $result;
    }

    private function format(&$from, &$to, $group) {
        switch ($group) {
            case 1:
                $days = ($to - $from)/86400;
                if ($days > 20) {
                    $from = strtotime('-20 days', $to);
                } else if ($days < 5) {
                    $from = strtotime('-5 days', $to);
                }
            break;
            case 2:
                $weeks = ($to - $from)/604800;
                if ($weeks > 20) {
                    $from = strtotime('-20 weeks', $to);
                } else if ($weeks < 5) {
                    $from = strtotime('-5 weeks', $to);
                }
            break;
            case 3:
                $months = ($to - $from)/2592000;
                if ($months > 10) {
                    $from = strtotime('-10 months', $to);
                } else if ($months < 5) {
                    $from = strtotime('-5 months', $to);
                }
            break;
        }
    }
    
    private function transform_date($date, $group) {
        if (strpos($date, '-') !== FALSE) {
            $array = explode('-', $date);
            $date = $this->transform_date($array[0], $group).', '.$this->transform_date($array[1], $group);
            return $date;
        }
        
        if ($group == 1) {
            return date('d.m', strtotime($date));
        } else if ($group == 2) {
            $year = substr($date, 3, 4);
            $week = (int) substr($date, 0, 2) - 1;
            $day_of_week = date('N', mktime(0, 0, 0, 1, 1, $year));
            if ($day_of_week > 1) {
                $day_of_week = 9 - $day_of_week;
            }
            $date = date('d.m.Y', mktime(0, 0, 0, 1, $week*7 + $day_of_week, $year));
            return $date;
        } else if ($group == 3) {
            $year = (int) substr($date, 3, 4);
            $month = (int) substr($date, 0, 2);
            $months = array('Нулябрь','Январь','Февраль','Март','Апрель','Май','Июнь','Июль','Август','Сентябрь','Октябрь','Ноябрь','Декабрь');
            $month = $months[$month];
            //$time = strtotime('01.'.$month.'.'.$year);
            //$date = date('d.m.Y', $time);
            return $month.' '.$year;
        }
    }
    
}
